package com.whut.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whut.common.JosnUtil;
import com.whut.common.Message;
import com.whut.common.UserUtil;
import com.whut.common.ValidateCodeUtils;
import com.whut.entity.Courier;
import com.whut.entity.User;
import com.whut.service.CourierService;
import com.whut.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户列表
     * @return
     */
    @PostMapping("/list.do")
    public List<User> list() {
        List<User> list = userService.list();
        return list;
    }

    /**
     * 增加用户
     * @param user
     * @return
     */
    @PostMapping("/insert.do")
    public String insert(@RequestBody User user) {
        user.setLoginTime(LocalDateTime.now());

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserPhone, user.getUserPhone());
        User user1 = userService.getOne(wrapper);

        if (user1 != null) {
            return "bound";
        }

        userService.save(user);
        return "success";
    }

    /**
     * 根据电话查找用户信息
     * @param request
     * @return
     */
    @PostMapping("/hasUser.do")
    public Message<User> hasUser(HttpServletRequest request) {
        String userPhone = request.getParameter("tel");

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userPhone != null, User::getUserPhone, userPhone);
        User user = userService.getOne(wrapper);

        if (user == null) {
            return Message.error("fail");
        } else {
            return Message.success(user);
        }
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @PostMapping("/update.do")
    public String update(@RequestBody User user) {
        log.info(user.toString());

        userService.updateById(user);
        return "success";
    }

    /**
     * 删除用户
     * @param request
     * @return
     */
    @RequestMapping("/delete.do")
    public String delete(HttpServletRequest request) {
        userService.removeById(request.getParameter("id"));
        return "success";
    }


}
